package com.lagou.service.impl;

import com.lagou.dao.CodeDao;
import com.lagou.pojo.AuthCode;
import com.lagou.service.CodeService;
import com.lagou.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Date;
import java.util.Optional;

@Service
@Slf4j
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeDao codeDao;

    @Reference
    private EmailService emailService;

    /**
     * 生成code
     * @param email
     * @return
     */
    @Override
    public boolean createCode(String email) {
        int code = RandomUtils.nextInt(999999);
        code = code < 100000 ? code + 100000 : code;

        AuthCode authCode = AuthCode.builder()
                .code(code + "")
                .email(email)
                .createtime(new Date())
                .expiretime(DateUtils.addMinutes(new Date(), 10))
                .build();

        try {
            codeDao.save(authCode);
            emailService.sendEmail(email,code+"");
            return true;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return false;
        }
    }

    /**
     * 验证code 有效
     * @param email
     * @param code
     * @return
     */
    @Override
    public int validateCode(String email, String code) {
        AuthCode authCode = AuthCode.builder()
                .email(email)
                .code(code)
                .build();

        Example example = Example.of(authCode);

        Optional<AuthCode> optional = codeDao.findOne(example);

        if(optional.isPresent()){
            AuthCode code1 = optional.get();
            if(code1.getExpiretime().getTime() > System.currentTimeMillis()){
                return 0;
            }else {
                return 2;
            }
        }else {
            return 1;
        }
    }
}
